import axios from 'axios'
import router from "@/router"
import msg from '@/assets/js/toast'
import emas from '@csair/windvane-api-ehome'
import { configs } from './baseUrl'

export function request (config) {
  // 配置请求的根路径
  const instance = axios.create({
    baseURL: configs[process.env.NODE_ENV].baseUrl,
    // baseURL: '/api',
    timeout: 30000
  })
  const err = (error) => {
    let text = ''
    if (error.response) {
      if (error.response.status === 404) {
        text = error.response.status +' '+ error.response.statusText
        return Promise.reject(text)
      }
      if (error.response.status === 413) {
        return Promise.reject("最大上传文件大小为50M")
      }
    }
    return Promise.reject(error)
  }
  // 请求拦截
  instance.interceptors.request.use(config => {
    if (config.url.indexOf('userInfo') == -1) msg.loading()
    const token = window.sessionStorage.getItem('token')
    if (token) config.headers['Access-Token'] = token
    return config
  }, err)
  // 响应拦截
  instance.interceptors.response.use(res => {
    if (res.config.url.indexOf('userInfo') === -1) msg.hideLoading()
    if (res.data.status === 501) {
      setTimeout(() => {
        window.sessionStorage.removeItem('token')
        emas.EmasCubeLogin.logout()
        router.push('/').catch(err => console.log(err))
      }, 1000)
      return Promise.reject(res.data.msg || res.data.message || '请求超时,请稍后再试！')
    }
    if (res.data.status === 400) {
      return Promise.reject(res.data.message)
    }
    if (res.config.url.indexOf("getCaptcha") !== -1) {
      return res
    }
    return res.data
  }, err)

  return instance(config)
}
